<?php

class FileUploadHandler {

	private $m_db = null;
	// Kontruktorn till klassen där vi matar in en databas.
	public function __construct(Database $db) {
		$this -> m_db = $db;
	}

	// Kollar om datatyperna stämmer som vi ska ha
	public function CheckFile($file) {

		if ((($file["file"]["type"] === "image/png") || ($file["file"]["type"] === "image/jpeg") || ($file["file"]["type"] === "image/jpg"))) {

			// Kollar om namnet redan finns
			if (file_exists("files/" . $file["file"]["name"])) {
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

	// Spar fil i mappen files
	public function SaveFile($file) {
		move_uploaded_file($file["file"]["tmp_name"], "files/" . $file["file"]["name"]);
	}

	// RegisterFile, spar namn och titel i databas
	public function RegisterFile($title, $filename, $username) {
		$sqlQuery = "INSERT INTO file(title,filename, username) VALUES(?, ?, ?)";

		$stmt = $this -> m_db -> Prepare($sqlQuery);
		$result = $stmt -> bind_param('sss', $title, $filename, $username);
		if ($this -> m_db -> execute($stmt) === 0) {
			return true;
		}
		return false;
	}

	// GetTitle, hämtar titel där namnet är den man trycker på
	public function GetPicture($name) {
		$sqlQuery = "SELECT pk, title, username, date FROM file WHERE filename = ?";

		$id = Null;
		$title = Null;
		$username = Null;
		$date = Null;

		$stmt = $this -> m_db -> Prepare($sqlQuery);

		$stmt -> bind_param('s', $name);

		$this -> m_db -> execute($stmt);

		$stmt -> bind_result($id, $title, $username, $date);

		while ($r = $stmt -> fetch()) {
			$Picture = new Picture($id, $title, $username, $date);

			return $Picture;
		}
	}
		// Kollar om namnet redan finns i databasen
	public function DoExists($name) {
		$sqlQuery = "SELECT filename FROM file WHERE filename = ?";

		$stmt = $this -> m_db -> Prepare($sqlQuery);

		$stmt -> bind_param('s', $name);

		if ($this -> m_db -> execute($stmt) > 0) {
			return true;
		}
		return false;

	}


}
